package com.poizon.infrastructure.center.config.starter.nacos;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;

import java.util.Arrays;

/**
 * 注册nacos监听器
 */
@Slf4j
public class NacosChangeListenerRegister implements ApplicationRunner {
    public static final String SPRING_APPLICATION_NAME = "spring.application.name";
    public static final String NACOS_CONFIG_GROUP = "nacos.config.group";
    public static final String NACOS_CONFIG_SHARED_DATAIDS = "nacos.config.shared-dataids";

    @Value("${" + SPRING_APPLICATION_NAME + "}")
    private String appName;
    @Value("${" + NACOS_CONFIG_GROUP + ":DEFAULT_GROUP}")
    private String group;
    @Value("${" + NACOS_CONFIG_SHARED_DATAIDS + "}")
    private String sharedDataIds;

    private ConfigService configService;
    private NacosChangeListener configChangeListener;
    private Environment environment;

    public NacosChangeListenerRegister(ConfigService configService, NacosChangeListener configChangeListener, Environment environment) {
        this.configService = configService;
        this.configChangeListener = configChangeListener;
        this.environment = environment;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Assert.notNull(configService);
        Assert.notNull(configChangeListener);
        log.info(">注册nacos配置变更监听器");

        // todo: 根据nacos配置,手动读取配置添加更多配置的监听器
        Assert.notNull(appName, "应用名称不能为空");
        configService.addListener(appName + ".yml", group, configChangeListener);
        configService.addListener(appName + ".properties", group, configChangeListener);
        Arrays.stream(sharedDataIds.split(",")).forEach(s -> {
            try {
                configService.addListener(s, group, configChangeListener);
            } catch (NacosException e) {
                log.error(StrUtil.format(">监听={}失败", s), e);
            }
        });
    }
}
